package com.agp.interceptor;

import com.agp.constant.JwtClaimsConstant;
import com.agp.context.BaseContext;
import com.agp.properties.JwtProperties;
import com.agp.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Slf4j
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            // 获取用户id
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户id:{}", userId);
            // 将当前用户id保存到当前线程中
            BaseContext.setCurrentId(userId);
            // 3、通过，放行
            return true;
        } catch (Exception e) {
            // 4、不通过，响应401状态码
            log.error("jwt校验失败：{}", e.getMessage());
            response.setStatus(401);
            return false;
        }

    }
}
